package com.za.apm.cat.util;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.dianping.cat.Cat;
import com.dianping.cat.Cat.Context;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Request.Builder;
import okhttp3.Response;

/**
 * 类HttpUtils.java的实现描述：
 * 
 * @author: tongyufu 2017-11-22 14:39:30
 */
public class HttpUtils {

	public static Response doGet(String url) {
		OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(10, TimeUnit.MINUTES)
				.readTimeout(10, TimeUnit.MINUTES).build();
		Builder build = new Request.Builder();
		HttpServletRequest req = HttpUtils.getRequest();
		Cat.Context context = (Context) req.getAttribute("_cat_context");
		// build.addHeader(Context.CHILD, context.getProperty(Context.CHILD));
		// build.addHeader(Context.PARENT, context.getProperty(Context.PARENT));
		// build.addHeader(Context.ROOT, context.getProperty(Context.ROOT));
		build.url(url);
		try {
			return client.newCall(build.build()).execute();
		} catch (IOException e) {
			Cat.logError(e);
			throw new RuntimeException(e);
		}
	}

	public static HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}
}
